﻿using System.Linq;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Drivers;
using Orchard.Media.Services;
using Szmyd.Orchard.Modules.Silverlight.Models;
using Szmyd.Orchard.Modules.Silverlight.Settings;

namespace Szmyd.Orchard.Modules.Silverlight.Drivers
{
    public class SilverlightPartDriver : ContentPartDriver<SilverlightPart>
    {
        private readonly IMediaService _mediaService;

        public SilverlightPartDriver(IMediaService mediaService)
        {
            _mediaService = mediaService;
        }

        protected override DriverResult Display(SilverlightPart part, string displayType, dynamic shapeHelper) {
            return ContentShape(shapeHelper.Parts_Silverlight_Silverlight(ContentPart: part));
        }

        protected override DriverResult Editor(SilverlightPart part, dynamic shapeHelper)
        {
            var files = _mediaService
                .GetMediaFiles("Silverlight")
                .Where(f => f.Type == ".xap")
                .Select(f => new
                    {
                        Path = _mediaService.GetPublicUrl("Silverlight/" + f.Name),
                        f.Name
                    }
                )
                .ToList();
            var settings = part.Settings.GetModel<SilverlightPartTypePartSettings>();

            part.AvailableFiles = files;
            part.AllowSourceChange = string.IsNullOrWhiteSpace(settings.DefaultSource);
            if (!part.AllowSourceChange)
                part.Source = settings.DefaultSource;
            part.AllowInitParamsChange = string.IsNullOrWhiteSpace(settings.DefaultInitParams);
            if (!part.AllowInitParamsChange)
                part.InitParams = settings.DefaultInitParams;

            return ContentShape("Parts_Silverlight_Silverlight",
                                () => shapeHelper.EditorTemplate(TemplateName: "Parts/Silverlight.Silverlight", Model: part, Prefix: Prefix));
        }

        protected override DriverResult Editor(SilverlightPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            updater.TryUpdateModel(part, Prefix, null, null);
            return Editor(part, shapeHelper);
        }
    }
}